﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TCPTest
{
    class Program
    {
        private static byte[] result = new byte[1024];
        private static int myProt = 1234;   //端口
        static Socket serverSocket;

        static void Main(string[] args)
        {
          //  Thread server_Thread = new Thread(new ThreadStart(ServerStart));
          // server_Thread.Start();

            //服务器IP地址
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serverSocket.Bind(new IPEndPoint(ip, myProt));  //绑定IP地址：端口
            serverSocket.Listen(10);    //设定最多10个排队连接请求
            Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString());
            //通过Clientsoket发送数据
            Thread myThread = new Thread(ListenClientConnect);
            myThread.Start();
            Console.ReadLine();
        }


        /// <summary>
        /// 监听客户端连接
        /// </summary>
        private static void ListenClientConnect()
        {
            while (true)
            {
                Socket clientSocket = serverSocket.Accept();
                clientSocket.Send(Encoding.UTF8.GetBytes("Server Say Hello"));
                Thread receiveThread = new Thread(ReceiveMessage);
                receiveThread.Start(clientSocket);
            }
        }

        /// <summary>
        /// 接收消息
        /// </summary>
        /// <param name="clientSocket"></param>
        private static void ReceiveMessage(object clientSocket)
        {
            Socket myClientSocket = (Socket)clientSocket;
            while (true)
            {
                try
                {
                    //通过clientSocket接收数据
                    int receiveNumber = myClientSocket.Receive(result);
                    Console.WriteLine("接收客户端{0}消息{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(result, 0, receiveNumber));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    myClientSocket.Shutdown(SocketShutdown.Both);
                    myClientSocket.Close();
                    break;
                }
            }
        }

      /*  private static void ServerStart()
        {
            //创建IPEndPoint
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234);
            //创建Socket实例
            Socket server_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //绑定Socket与IPEndPoint
            server_Socket.Bind(ipep);
            //设置Socket收听模式
            server_Socket.Listen(10);

            while (true)
            {
                try
                {
                    //接受Andorid信息
                    Socket client_Socket = server_Socket.Accept();
                    
                //    Thread client_Thread = new Thread(new ThreadStart(ReceiveAndroidData));
                //    client_Thread.Start(client_Socket);

                    Thread client_Thread = new Thread(ReceiveAndroidData);
                    client_Thread.Start(client_Socket);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("start error: " + ex.Message);
                }

            }
        }

        private static void ReceiveAndroidData(object client_Socket)
        {
            bool keepalive = true;
            Socket socketclient = (Socket)client_Socket;
            Byte[] buffer = new Byte[1024];

            //根据收听到的客户端套接字向客户端发送信息
            IPEndPoint clientep = (IPEndPoint)socketclient.RemoteEndPoint;
            Console.WriteLine("Andorid Client：" + clientep.Address + "：" + clientep.Port);
            string str = "connect server----- ";
            byte[] data = new byte[1024];
            data = Encoding.ASCII.GetBytes(str);
            socketclient.Send(data, data.Length, SocketFlags.None);

            while (keepalive)
            {
                //在套接字上接收客户端发送的信息
                int buffer_lenght = 0;
                try
                {
                    buffer_lenght = socketclient.Available;

                    socketclient.Receive(buffer, 0, buffer_lenght, SocketFlags.None);
                    if (buffer_lenght == 0)
                        continue;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("receive error:" + ex.Message);
                    return;
                }
                clientep = (IPEndPoint)socketclient.RemoteEndPoint;
                string strAndroid_CMD = System.Text.Encoding.ASCII.GetString(buffer).Substring(0, buffer_lenght);
            }

            //对根据strAndroid_CMD到数据库中查询值
        }*/
    }
}
